#include "projection.h"

#include <cmath>

qreal Projection::lon2rawx(qreal lon)
{
    return (lon + 180.0) / 360.0;
}
 
qreal Projection::lat2rawy(qreal lat)
{
    return (1.0 - log(tan(lat * M_PI/180.0) + 1.0 / cos(lat * M_PI/180.0)) / M_PI) / 2.0;
}

qreal Projection::lon2tilex(qreal lon, int z)
{
    return (lon + 180.0) / 360.0 * (1 << z);
}
 
qreal Projection::lat2tiley(qreal lat, int z)
{
    return (1.0 - log(tan(lat * M_PI/180.0) + 1.0 / cos(lat * M_PI/180.0)) / M_PI) / 2.0 * (1 << z);
}
 
qreal Projection::tilex2lon(qreal x, int z)
{
    return x / (1 << z) * 360.0 - 180;
}
 
qreal Projection::tiley2lat(qreal y, int z)
{
    qreal n = M_PI - 2.0 * M_PI * y / (1 << z);
    return 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
}

QString Projection::geo2string(const QPointF &geo)
{
    QString lat = geo.y() > 0 ? QString("N %1").arg(geo.y()) : QString("S %1").arg(-geo.y());
    QString lon = geo.x() > 0 ? QString("E %1").arg(geo.x()) : QString("W %1").arg(-geo.x());
    return lat+" "+lon;
}

